package Arrays;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class _169_MajorityElement {
    //循环和判断，速度较慢
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> counts = new HashMap<Integer,Integer>();
        int max = Integer.MIN_VALUE;
        int length = nums.length;
        for(int i=0;i<length;i++){
            if(counts.get(nums[i])==null){
                counts.put(nums[i],1);
                if(max==Integer.MIN_VALUE){
                    max = nums[i];
                }
            }else{
                counts.replace(nums[i],counts.get(nums[i])+1);
                if(counts.get(nums[i])>counts.get(max)) {
                    max = nums[i];
                }
            }
        }
        return max;
    }

    public int majorityElement1(int[] nums){
        Arrays.sort(nums);
        return nums[(nums.length+1)/2];
    }
}
